<?php namespace models;
use helpers\Helper as Helper;
/**
 * This code is property of Piotr Poradzisz. Do not distribute under threat of legal consequences.
 * All rights reserved.
 * Все права защищены.
 * Alle Rechte vorbehalten.
 * Todos los derechos reservados.
 * Wszelkie prawa zastrzeżone.
 *                  جميع الحقوق محفوظة
 * 保留所有权利
 * すべての著作権
 * @author Piotr Poradzisz
 * email: piotr.poradzisz@gmail.com
 * tel.: +48668027020
 */
class Select extends Field{
    public static function multiSelectAdd($fieldId, $itemId){
        $mysql = new Mysql();
        $field = self::getFieldProperties($fieldId, 'f.referenceTable');
        $query = "SELECT childe FROM $field[referenceTable] WHERE parent = $itemId";
        $currantValues = $mysql->getTable($query);
        foreach ($_POST['options'] as $optionKey => $option) {
            if(Helper::multiDimensionalSearch($currantValues, 'childe', $option) === false){
                $query = "INSERT INTO $field[referenceTable] (parent, childe) VALUES ($itemId, $option)";
                $mysql->setQuery($query);
            }
        }
        return $response;
    }

    public function read($fieldId, $itemId){
        $this->setFieldProperties($fieldId, array('referenceTable', 'tableName'));
        $mysql = new Mysql();
        $query = "SELECT tn.id, tn.name, tr.id as 'referenceId' FROM $this->referenceTable tr LEFT JOIN $this->tableName tn ON (tr.childe = tn.id) WHERE tr.parent = $itemId ORDER BY tr.position ASC";
        return $mysql->getTable($query);
    }

    public function multiSelectDelete(){
        $field = self::getFieldProperties($_POST['fieldId'], 'f.referenceTable');
        $mysql = new Mysql();
        $query = "DELETE FROM $field[referenceTable] WHERE id = $_POST[optionId]";
        $mysql->setQuery($query);
        return 1;
    }

    public function multiSelectClear(){
        $field = self::getFieldProperties($_POST['fieldId'], 'f.referenceTable');
        $mysql = new Mysql();
        $query = "DELETE FROM $field[referenceTable] WHERE parent = $_POST[itemId]";
        $mysql->setQuery($query);
        return 1;
    }
}
?>